﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace SaiPuLSCoffee.model
{
    public class IOMsg
    {
        private static IOMsg instance;
        private IOMsg() { }

        public static IOMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new IOMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.PortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                IOSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.PortName, 38400, "", 8, 1);//其他串口通讯
                IOSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                Robot_Thr();
                All_thr = new Thread(AllMessages);
                All_thr.IsBackground = true;
                All_thr.Start();
            }
            catch (Exception)
            {
                IOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] result = new byte[IOSerialPort.Instance.serialPort.BytesToRead];
                IOSerialPort.Instance.serialPort.Read(result, 0, IOSerialPort.Instance.serialPort.BytesToRead);
                buffer.AddRange(result);
                string str = "";// $"{DateTime.Now}：\n";
                                //判断读写模式
                if (buffer.Count > 0x03)
                    str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                //Console.WriteLine(str);
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                            IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.AllMessage);
                        Thread.Sleep(100);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(100);
                    }

                }
            }
            catch (Exception)
            {
                IOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(200);
                IOSerial_Thr();
            }
        }
        public void Robot_Thr()
        {
            try
            {
                RobotOperate.Instance.Robot_Initialisation_double(); //机器人初始化
            }
            catch (Exception)
            {
                Thread.Sleep(100);
                Robot_Thr();
            }
        }
        #region 新的
        string strlist = "";
        public void MsgShow(string str)
        {
            try
            {
               // Console.WriteLine(str);
                nostrs = "";
                var nostr = str.Split(' ');
                nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
                for (int i = 1; i < nostr.Count() - 1; i++)
                {
                    nostrs += nostr[i] + " ";
                }
              //  Console.WriteLine(1);
                if (nostrs.Count() >= 5)
                {
                    if (nostrs.Substring(0, 5) == "01 05")
                    {
                        Console.WriteLine(str);
                    }
                    else if (nostrs.Substring(0, 5) == "01 04")
                    {
                        strlist = nostrs;
                    }
                    else
                    {
                        if (strlist != "")
                            strlist += nostrs;
                    }
                }
                if (strlist.Split(' ').Count() >= 105)
                {
                    //Console.WriteLine(2);
                    DigitalMsgBol2(strlist);
                    strlist = "";
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
        #endregion
        #region 旧的
        //public void MsgShow(string str)
        //{
        //    try
        //    {
        //        int count = str.Length / 315;
        //        if (count > 0)
        //        {
        //            var str1 = str.Substring(str.Length - count * 315, 315);
        //            //Console.WriteLine(str1);
        //            if (str1.Split(' ').Count() == 105)
        //            {
        //                DigitalMsgBol2(str1);
        //                if (count > 1)
        //                    MsgShow(str.Substring(str.Length - (count - 1) * 315, (count - 1) * 315));
        //            }
        //            else
        //            {
        //                var nostr = str1.Split(' ');
        //                int cc = int.TryParse(nostr[0].Substring(nostr[0].Length - 2, 2), out int a) ? a : -1;
        //                if (cc != -1)
        //                {
        //                    nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
        //                    for (int i = 1; i < nostr.Count() - 1; i++)
        //                    {
        //                        nostrs += nostr[i] + " ";
        //                    }
        //                    // Console.WriteLine(nostrs);
        //                    if (nostrs.Substring(0, 5) == "02 04")
        //                    {
        //                        if (nostrs.Count() >= 315)
        //                        {
        //                            DigitalMsgBol2(nostrs);
        //                            nostrs = "";
        //                        }
        //                    }
        //                    else
        //                    {
        //                        nostrs = "";
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {

        //            var nostr = str.Split(' ');
        //            nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
        //            for (int i = 1; i < nostr.Count() - 1; i++)
        //            {
        //                nostrs += nostr[i] + " ";
        //            }
        //            if (nostrs.Substring(0, 5) == "02 04")
        //            {
        //                if (nostrs.Count() >= 315)
        //                {
        //                    DigitalMsgBol2(nostrs);
        //                    nostrs = "";
        //                }
        //            }
        //            else
        //            {
        //                nostrs = "";
        //            }
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        return;
        //    }
        //}
        #endregion
        public void DigitalMsgBol2(string str)
        {
            try
            {
                //Console.WriteLine(str);
                var Bol = str.Split(' ');
                bool bol = false;
                if (WuLiaoCoffeeSel.Instance.Cup1_Sel_Bol != (Bol[4] == "01" ? true : false))
                {
                    bol = true;
                }
                if (CoffeeMakes.Instance.CFCCBol1 && !(Bol[4] == "01" ? true : false))
                {
                    CoffeeMakes.Instance.CFCCBol1 = false;
                }
                WuLiaoCoffeeSel.Instance.Cup1_Sel_Bol = Bol[4] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.Cup2_Sel_Bol != (Bol[6] == "01" ? true : false))
                {
                    bol = true;
                }
                if (CoffeeMakes.Instance.CFCCBol2 && !(Bol[6] == "01" ? true : false))
                {
                    CoffeeMakes.Instance.CFCCBol2 = false;
                }
                WuLiaoCoffeeSel.Instance.Cup2_Sel_Bol = Bol[6] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.CoffeeBean1_Sel_Bol != (Bol[8] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.CoffeeBean1_Sel_Bol = Bol[8] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.CoffeeBean2_Sel_Bol != (Bol[10] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.CoffeeBean2_Sel_Bol = Bol[10] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.CoffeeBean3_Sel_Bol != (Bol[12] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.CoffeeBean3_Sel_Bol = Bol[12] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.Sugar_Sel_Bol != (Bol[16] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.Sugar_Sel_Bol = Bol[16] == "01" ? true : false;
                //if (WuLiaoCoffeeSel.Instance.CupNew_Sel_Bol != (Bol[18] == "01" ? true : false))
                //{
                //    bol = true;
                //}
                //WuLiaoCoffeeSel.Instance.CupNew_Sel_Bol = Bol[18] == "01" ? true : false;
                if (bol)
                {

                    ClientList clientList = new ClientList();
                    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                    clientList.code = 2;
                    if (SocketServer.Instance.CoffeeSocket != null)
                        SocketServer.Instance.CoffeeSocket.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        #endregion
    }
}
